package com.zivwu.mvp.rx;

import com.zivwu.mvp.view.ILoadManager;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class DefObserver<T> implements Observer<T> {
    /**
     * 默认延迟时间
     */
    private static final int DEF_PROGRESSBAR_DELAY = 800;

    private Disposable mDisposable;
    private CompositeDisposable mDisposables;
    private ILoadManager mLoadManager;
    /**
     * 延迟展示loading的时间
     */
    private int mDelayTime;

    public DefObserver(CompositeDisposable mDisposable) {
        this(mDisposable, null);
    }

    public DefObserver(CompositeDisposable mDisposable, ILoadManager loading) {
        this(mDisposable, loading, DEF_PROGRESSBAR_DELAY);
    }

    public DefObserver(CompositeDisposable mDisposables,
                       ILoadManager mLoadManager,
                       int mDelayTime) {
        this.mDisposables = mDisposables;
        this.mLoadManager = mLoadManager;
        this.mDelayTime = mDelayTime;
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.mDisposable = d;
        if (mDisposables != null && mDisposable != null)
            mDisposables.add(d);
        loadingStart();
    }


    @Override
    public void onError(Throwable e) {
        onFinish();
    }

    @Override
    public void onComplete() {
        onFinish();
    }

    protected void onFinish() {
        loadingEnd();
    }

    private void loadingStart() {
        if (mLoadManager != null)
            mLoadManager.add(mDisposable, mDelayTime);
    }

    private void loadingEnd() {
        if (mLoadManager != null)
            mLoadManager.remove(mDisposable);
    }


}
